package ve.com.wayoyo.wuml_case.DibujoDiagramas;

import ve.com.wayoyo.wuml_case.NuevoDiagrama;
import ve.com.wayoyo.wuml_case.UserPref;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.ArrayAdapter;

import com.thoughtworks.xstream.XStream;

public class VistaDiagrama extends View {
	
	private static class _states{
		protected static int IDLE = 0;
		protected static int SCROLLING = 1;
		protected static int SCALING = 2;
		protected static int CREATING_ITEM = 3;
		protected static int MOVING_ITEM = 4;
		protected static int ITEM_SELECTED = 5;
		protected static int CONNECTING_ITEMS = 6;
		protected static int RESET = 99;
	}
	
	private static float MIN_ZOOM = 0.5f;
	private static float MAX_ZOOM = 3.0f;
	private static VistaDiagrama _instance;
	
	private int _xOffset = 0;
    private int _yOffset = 0;
    private float _Scale = 1.0f;
    private float initialDist;
    
    private int _xTouch = 0;
    private int _yTouch = 0;
    
    private int _currentState = _states.IDLE;
	
	private Diagrama _diagrama;
	private Paint _backgroundPaint;
	private Paint _imagePaint;
	
	private ScaleGestureDetector detector;
//	private String titulo = null;
	private boolean showHelpNewElement;
	
	private String str="";

	
	//Bitmaps de los cuadros de ayuda
	Bitmap HelpNewElementBitmap = BitmapFactory.decodeResource(this.getContext().getResources(),0x7f020000);

	public VistaDiagrama(Context context,Diagrama diagrama){
		super(context);
		_backgroundPaint = new Paint();
		_backgroundPaint.setColor(UserPref.getInstancia().getColorFondoDiagramas());
		this._diagrama = diagrama;
		_imagePaint = new Paint();
		detector = new ScaleGestureDetector(getContext(), new ScaleListener());
		_instance = this;
	}
	
	public Diagrama getDiagrama(){
		return _diagrama;
	}
	
	@Override
	protected void onDraw(Canvas c){
		super.onDraw(c);
		c.drawPaint(_backgroundPaint);
		_diagrama.Dibujar(c,_xOffset , _yOffset, _Scale);
		if(showHelpNewElement == true){
			c.drawBitmap(HelpNewElementBitmap, (c.getWidth()/2)-200, (c.getHeight()/2)-200, _imagePaint);
		}
		_imagePaint.setColor(Color.BLACK);
		c.drawText(str, 100-_xOffset, 100-_yOffset,_imagePaint);
		//invalidate();
	}
	
	@Override
	public boolean onTouchEvent (MotionEvent event) {
		detector.onTouchEvent(event);
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
            // store the current touch coordinates for scroll calculation
            _xTouch = (int) event.getX();
            _yTouch = (int) event.getY();
            if(_currentState != _states.CONNECTING_ITEMS){
            	_diagrama.resetFocus();
            }
            NuevoDiagrama diag = (NuevoDiagrama) this.getContext();	        
			if(_currentState == _states.CREATING_ITEM)
        	{			
		        Componente comp = new CompClase("");	
				Point anchor = new Point();
				
				anchor.set((int)((_xTouch)/(_Scale)-_xOffset), (int)((_yTouch)/(_Scale)-_yOffset));
				comp.setAnchor(anchor);
        		TituloComponente myDialog = new TituloComponente(this.getContext(),"Indique el nombre","Titulo",comp);
		        myDialog.show();
        		_currentState = _states.RESET;
        		showHelpNewElement = false;
        		invalidate();
        	}else if (_currentState == _states.CONNECTING_ITEMS){
        		Point touchPoint = new Point();
        		touchPoint.set((int)((_xTouch)/(_Scale)-_xOffset), (int)((_yTouch)/(_Scale)-_yOffset));
        		if(_diagrama.checkOnTouch(touchPoint,"Connect") == true){
        			_currentState = _states.ITEM_SELECTED;
        			invalidate();
        		}
        	}else{
        		Point touchPoint = new Point();
        		touchPoint.set((int)((_xTouch)/(_Scale)-_xOffset), (int)((_yTouch)/(_Scale)-_yOffset));
        		if(_diagrama.checkOnTouch(touchPoint,"Select") == true){
        			_currentState = _states.ITEM_SELECTED;
        	        diag.cambioMenu();
        			invalidate();
        		}else{

        			_currentState = _states.IDLE;

        			diag.menuPrincipal();

        			invalidate();
        		}
        	}
        }else if (event.getAction() == MotionEvent.ACTION_MOVE) {
            // touch starts moving, set the flag
        	if(_currentState == _states.IDLE){
	            _currentState = _states.SCROLLING;
        	}else if(_currentState ==  _states.ITEM_SELECTED){
        		_currentState = _states.MOVING_ITEM;
        	}
        	
        	if( _currentState == _states.SCROLLING || _currentState == _states.CONNECTING_ITEMS ){ 	
	            // get the new offset
        		_xOffset -= _xTouch - (int) event.getX();
        		_yOffset -= _yTouch - (int) event.getY();
        		invalidate();
        	}
        	if(_currentState == _states.MOVING_ITEM){
        		_diagrama.moverItemSeleccionado((int)(-(_xTouch - (int) event.getX())/_Scale),(int)(-(_yTouch - (int) event.getY())/_Scale));
        		invalidate();
        	}
    
         // store the last position
            _xTouch = (int) event.getX();
            _yTouch = (int) event.getY();
        } else if (event.getAction() == MotionEvent.ACTION_UP) {
            // touch released
        	//_isScaling = false;
        	initialDist = 0;
        	
        	
        }
		
		return true;
	}
	
	
	private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {

		@Override
		public boolean onScale(ScaleGestureDetector detector) {
				_currentState = _states.SCALING;
				_Scale *= detector.getScaleFactor();
				_Scale = Math.max(MIN_ZOOM, Math.min(_Scale, MAX_ZOOM));
				invalidate();
			return true;
		}

	}
	
	public static VistaDiagrama getVista(){
		return _instance;
	}
	
	public static void resetFocusStatico(){
		_instance.getDiagrama().resetFocus();
		_instance.invalidate();
	}

	public void Conexion() {
		_currentState = _states.CONNECTING_ITEMS;	
	}

	public void nuevaClase()
	{
		_currentState=_states.CREATING_ITEM;
		showHelpNewElement = true;
		invalidate();
	}
	
	public void agregarAtributo() {
		AtributoComponente myDialog = new AtributoComponente(this.getContext());		
        myDialog.show();
		invalidate();
	}
	
	public void modificarAtributo() {
		AtributoModif myDialog = new AtributoModif(getContext());
		myDialog.show();
		invalidate();
	}

	public String exportar() {
		
		XStream xs = new XStream();
		String str = xs.toXML(_diagrama);
//		File root = Environment.getRootDirectory();
//        File file = new File(root, "tomato50.txt");	 
		
//		invalidate();
		return str;
		
	}

	public void agregarMetodo() {
		NuevoMetodoComponente myDialog = new NuevoMetodoComponente(this.getContext());		
        myDialog.show();
		invalidate();		
	}

	public void modificarMetodo(ArrayAdapter<String> adapter) {
		SeleccionarMetodoComponente myDialog = new SeleccionarMetodoComponente(this.getContext(), adapter);		
        myDialog.show();
		invalidate();
	}

}


